package com.example.exception;

import com.example.model.GeneralResult;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.quarkus.hibernate.validator.runtime.jaxrs.ResteasyReactiveViolationException;
import io.quarkus.runtime.util.StringUtil;
import jakarta.inject.Inject;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ValidationException;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.ext.ExceptionMapper;
import jakarta.ws.rs.ext.Provider;
import lombok.extern.slf4j.Slf4j;

/**
 * 指定处理 ValidationException 异常
 */
@Slf4j
@Provider
public class ValidationExceptionMapper implements ExceptionMapper<ValidationException>  {

    @Inject
    ObjectMapper objectMapper;

    @Override
    public Response toResponse(ValidationException exception) {
        if (!(exception instanceof ResteasyReactiveViolationException)) {
            throw exception;
        }

        String message = "";
        for (ConstraintViolation<?> violation : ((ResteasyReactiveViolationException) exception).getConstraintViolations()) {
            if (StringUtil.isNullOrEmpty(violation.getMessage())) {
                continue;
            }
            message = violation.getMessage();
            break;
        }

        GeneralResult<String> result = GeneralResult.error(message);
        try {
            String jsonString = objectMapper.writeValueAsString(result);
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(jsonString).build();
        } catch (JsonProcessingException e) {
            log.error("JSON处理异常", e);
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
        }
    }
}
